package saa.dao.usuario;

import java.io.Serializable;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import saa.dominio.usuario.Aluno;

@Stateless
public class AlunoDAO implements AlunoDAOInterface, Serializable {

    @PersistenceContext(unitName = "SAAPU")
    private EntityManager em;

    public AlunoDAO() {
        super();
    }

    public List<Aluno> listar() {
        try {
            return em
                    .createNamedQuery("Alunos", Aluno.class)
                    .getResultList();
        } catch (Exception e) {
            return null;
        }
    }

    public Aluno buscar(long alunoId) {
        try {
            return em
                    .find(Aluno.class, alunoId);
        } catch (Exception e) {
            return null;
        }
    }

    public List<Aluno> buscarPerfisUsuario(long usuarioId) {
        try {
            return em
                    .createNamedQuery("Aluno.usuario.id", Aluno.class)
                    .setParameter("id", usuarioId)
                    .getResultList();
        } catch (Exception e) {
            return null;
        }
    }

    public Aluno buscar(long usuarioId, long cursoId) {
        try {
            return em
                    .createNamedQuery("Aluno.usuario.id,curso.id", Aluno.class)
                    .setParameter("usuarioId", usuarioId)
                    .setParameter("cursoId", cursoId)
                    .getSingleResult();
        } catch (Exception e) {
            return null;
        }
    }

    public boolean adicionar(Aluno aluno) {
        try {
            if (buscar(aluno.getUsuario().getId(), aluno.getCurso().getId()) == null) {
                em.persist(aluno);
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
}
